package com.jpxx.netty.chaibao;

import java.net.InetSocketAddress;

import io.netty.bootstrap.ServerBootstrap;  
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;  
import io.netty.channel.ChannelInitializer;  
import io.netty.channel.ChannelOption;  
import io.netty.channel.EventLoopGroup;  
import io.netty.channel.nio.NioEventLoopGroup;  
import io.netty.channel.socket.SocketChannel;  
import io.netty.channel.socket.nio.NioServerSocketChannel;  
import io.netty.handler.codec.DelimiterBasedFrameDecoder;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;  
import io.netty.handler.codec.string.StringEncoder;  


//定义分隔符解决

public class Server {  
	  
    private int port;  
      
    public Server(int port) {  
        this.port = port;  
    }  
    public void start(){  
        EventLoopGroup pGroup = new NioEventLoopGroup();//一个用户服务器端接收客户端连接的
        EventLoopGroup cGroup = new NioEventLoopGroup();//进行网络通信（网络读写）
		try {
			ServerBootstrap b = new ServerBootstrap();// 2.创建辅助工具类，用于服务器通道配置
			b.group(pGroup, cGroup)// 绑定2个线程组
					.channel(NioServerSocketChannel.class)// 指定NIO模式
					.option(ChannelOption.SO_BACKLOG, 1024)// 设置tcp缓冲区
					.childOption(ChannelOption.SO_SNDBUF, 32 * 1024)// 设置发送缓冲大小
					.option(ChannelOption.SO_RCVBUF, 32 * 1024)// 这是接收缓冲大小
					.childOption(ChannelOption.SO_KEEPALIVE, true)// 保持连接
					.childHandler(new ChannelInitializer<SocketChannel>() {
						@Override
						protected void initChannel(SocketChannel sc) throws Exception {
							//设置分隔符
							ByteBuf buf = Unpooled.copiedBuffer("/r/n".getBytes());//通过工具类转成buf类型
							//设置字符串形式的解码   此处1024指的是分隔符的大小范围
							sc.pipeline().addLast(new DelimiterBasedFrameDecoder(1024,buf));
							//设置字符串形式的解码
							sc.pipeline().addLast("decoder", new StringDecoder());  
							//sc.pipeline().addLast("encoder", new StringEncoder());
							
							sc.pipeline().addLast(new ServerHandler()); // 3. 在这里配置具体接收数据方法的处理
						};
					});

			// 绑定端口，开始接收进来的连接
			ChannelFuture cf1 = b.bind(port).sync(); // 4.进行绑定
			System.out.println("服务器启动，监听" + port + "端口号");

			cf1.channel().closeFuture().sync();// 5等待关闭
			System.out.println("server关闭调用");
		} catch (Exception e) {
			pGroup.shutdownGracefully();
			cGroup.shutdownGracefully();
		}
    }  
      
    public static void main(String[] args) throws Exception {  
        int port;  
        if (args.length > 0) {  
            port = Integer.parseInt(args[0]);  
        } else {  
            port = 8765;//这是端口号 
        }  
        new Server(port).start();  
    }  
}  